var gulp = require("gulp"),
    imagemin = require('gulp-imagemin'), //压缩图片1
    tinypng = require('gulp-tinypng-compress'), //压缩图片2 需要有KEY,下面有将怎样获取KEY值
    tinypng_nokey = require('gulp-tinypng-nokey'), //压缩图片3 免费
    runSequence = require('run-sequence');
var spritesmith = require("gulp.spritesmith");
var gulpif = require("gulp-if");
//图片压缩1 (感觉压缩程度不够)
gulp.task('compress_img', function () {
    gulp.src('src/images/**/*')
        .pipe(imagemin({
            optimizationLevel: 5, //类型：Number  默认：3  取值范围：0-7（优化等级）
            progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
            interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
            multipass: true //类型：Boolean 默认：false 多次优化svg直到完全优化
        }))
        .pipe(gulp.dest('dist/images/image_min'))
});

//压缩图片2 (需要有KEY,并且每个月只有500张)
gulp.task('tinypng', function () {
    gulp.src('src/images/**/*')
        .pipe(tinypng({
            key: 'z6pfDN1YKYSXTGlk0cDBcxwSgqqDrCPj',
            sigFile: 'dist/images/.tinypng-sigs',
            log: true
        }))
        .pipe(gulp.dest('dist/images/tiny-sigs'));
})

//压缩图片3 (免费 常用)
gulp.task('tp', function () {
    gulp.src('src/images/**/*')
        .pipe(tinypng_nokey())
        .pipe(gulp.dest('dist/images/tiny_nokey'));
})

//合并图片
gulp.task('sprites', function () {
    return gulp.src('src/*.png')
        .pipe(spritesmith({
            imgName: 'sprite.png',
            cssName: 'sprite.css',
            padding:1000,//合并时两个图片的间距
            algorithm: 'top-down',//注释1  top-down、left-right、diagonal、alt-diagonal、binary-tree
        }))
        .pipe(gulpif('*.png', gulp.dest('dist/img/')))
        .pipe(gulpif('*.css', gulp.dest('dist/css/')));
});

gulp.task('default', function (done) {
    condition = false;
    runSequence(
        'compress_img',
        'tinypng',
        'tp',
        done);
});